package xyz.hubery.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.springframework.stereotype.Service;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import xyz.hubery.domain.Account;
import xyz.hubery.domain.CashRecharge;
import xyz.hubery.dto.UserDTO;
import xyz.hubery.feign.UserFeign;
import xyz.hubery.mapper.AccountDetailMapper;
import xyz.hubery.domain.AccountDetail;
import xyz.hubery.service.AccountDetailService;
import xyz.hubery.service.CoinService;

@Service
public class AccountDetailServiceImpl extends ServiceImpl<AccountDetailMapper, AccountDetail> implements AccountDetailService{

    @Autowired
    private UserFeign userFeign;
    @Autowired
    private CoinService coinService;

    @Override
    public boolean addAccountDetail(Account account, Long orderId, Byte direction, String bussinessType, BigDecimal mum, BigDecimal fee, String remark) {
        // 添加一条流水记录
        AccountDetail accountDetail = new AccountDetail();
        accountDetail.setUserId(account.getUserId());
        accountDetail.setCoinId(account.getCoinId());
        accountDetail.setAccountId(account.getId());
        accountDetail.setRefAccountId(account.getId());
        accountDetail.setOrderId(orderId);
        accountDetail.setDirection((byte) 1);
        accountDetail.setBusinessType(bussinessType);
        accountDetail.setAmount(mum);
        accountDetail.setFee(fee);
        accountDetail.setRemark(remark);
       return save(accountDetail);
    }

    @Override
    public Page<AccountDetail> findPage(Long userId, String userName, String mobile, Integer amountStart, Integer amountEnd, Long accountId, String startTime, String endTime, Page<AccountDetail> page) {

        LambdaQueryWrapper<AccountDetail> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(userId != null, AccountDetail::getUserId, userId);
        wrapper.eq(accountId != null, AccountDetail::getAccountId, accountId);
        wrapper.between(amountStart != null && amountEnd != null, AccountDetail::getAmount, amountStart, amountEnd);
        wrapper.between(startTime != null && endTime != null, AccountDetail::getCreated, startTime, endTime);

        Page<AccountDetail> accountDetailPage = page(page, wrapper);
        List<Long> userIds = new ArrayList<>();
        // 获取用户id列表
        if(userId != null) {  // 直接根据userId查询
            userIds.add(userId);
        }else{ // 提取用户id列表
            userIds = accountDetailPage.getRecords().stream().map(AccountDetail::getUserId).distinct().collect(Collectors.toList());
        }
        if(CollectionUtils.isEmpty(userIds)) {
            return accountDetailPage;
        }
        // 远程调用根据用户id列表查询用户信息
        List<UserDTO> userDTOList = userFeign.getBasicUserInfo(userIds);
        // 转换为map结构
        Map<Long, UserDTO> userDTOMap = userDTOList.stream().collect(Collectors.toMap(UserDTO::getId, user -> user));
        // 提取出符合条件的充值记录
        List<AccountDetail> filteredRecords = new ArrayList<>();
        Set<Long> filterIds = new HashSet<Long>();
        for (UserDTO userDTO : userDTOList) {
            boolean match = true;
            if(!StringUtils.isEmpty(userName) && !userDTO.getUsername().contains(userName)) { //根据用户名进行匹配
                match = false;
            }
            if(!StringUtils.isEmpty(mobile) && !userDTO.getMobile().contains(mobile)) { //根据手机号进行匹配
                match = false;
            }
            if(match) {
                filterIds.add(userDTO.getId());
            }
        }

        List<AccountDetail> records = accountDetailPage.getRecords();
        for (AccountDetail record : records) {
            if(filterIds.contains(record.getUserId())) {
                // 填充用户信息
                UserDTO userDTO = userDTOMap.get(record.getUserId());
                record.setUsername(userDTO.getUsername());
                // 查询coinName
                String coinName = coinService.getById(record.getCoinId()).getName();
                record.setCoinName(coinName);
                filteredRecords.add(record);
            }
        }

        // 替换为过滤后的记录
        accountDetailPage.setRecords(filteredRecords);
        accountDetailPage.setTotal(filteredRecords.size());
        return accountDetailPage;
    }
}
